package com.jixiang.dictionary.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixiang.dictionary.dao.DsRegionDao;
import com.jixiang.model.dictionary.entity.DsRegion;
import com.jixiang.dictionary.service.DsRegionService;
import com.jixiang.model.common.dtos.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.jixiang.common.constants.RedisConstants.REDIS_PREX_REGION;

/**
 * (DsRegion)表服务实现类
 *
 * @author makejava
 * @since 2023-11-05 02:46:55
 */
@Service("dsRegionService")
public class DsRegionServiceImpl extends ServiceImpl<DsRegionDao, DsRegion> implements DsRegionService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public ResponseResult getRegion(String parentId) {
        List<DsRegion> list = renewRegin(parentId);
        return ResponseResult.okResult(list);
    }

    public List<DsRegion> renewRegin(String parentId){
        String rediaData = stringRedisTemplate.opsForValue().get(REDIS_PREX_REGION + parentId);
        if(StrUtil.isNotBlank(rediaData)){
            List<DsRegion> list = JSONUtil.toList(rediaData, DsRegion.class);
            return  list;
        }
        if(rediaData != null){
            return null;
        }
        List<DsRegion> list = query().eq("parent_id", parentId).orderByAsc("id").list();
        if(list == null || list.isEmpty()){
            stringRedisTemplate.opsForValue().set(REDIS_PREX_REGION + parentId,"",3, TimeUnit.HOURS);
        }else {
            JSONArray jsonArray = JSONUtil.parseArray(list);
            stringRedisTemplate.opsForValue().set(REDIS_PREX_REGION + parentId,jsonArray.toString());
        }
        return list;
    }

}

